package com.mudrov.anagram.helpers;

import com.mudrov.expeptions.FilesExceptions;

import java.io.*;

public class FilePiecedReader implements InputTextReader, AutoCloseable {

    private BufferedReader readerFromFile;
    private int pieceSize;
    private boolean hasNextPiece = true;

    public FilePiecedReader(String fileName, int pieceSize) {

        try {
            readerFromFile = new BufferedReader(new FileReader(fileName));
        } catch (FileNotFoundException e) {
            throw new FilesExceptions(e);
        }
        this.pieceSize = pieceSize;
    }

    public FilePiecedReader(File file, int pieceSize) throws FileNotFoundException, UnsupportedEncodingException {
        readerFromFile = new BufferedReader(new FileReader(file));
        this.pieceSize = pieceSize;
    }

    @Override
    public String getNextPieceOfText() {
        StringBuilder resultString = new StringBuilder("");

        for (int i = 0; i < pieceSize; ++i) {
            String readLine = null;
            try {
                readLine = readerFromFile.readLine();
            } catch (IOException e) {
                readLine = null;
            }
            if (readLine == null) {
                hasNextPiece = false;
                break;
            }
            resultString.append(readLine + " ");
        }
        return resultString.toString();
    }

    @Override
    public boolean hasNextPiece() {
        return hasNextPiece;
    }

    @Override
    public void close() {
        try {
            readerFromFile.close();
        } catch (IOException e) {
            //NOP
        }
    }

}
